#!/usr/bin/env python

# encoding: utf-8

'''
 * Create File __init__.py
 * Created by leixu on 2017/11/9
 * IDE PyCharm
'''
from abc import abstractmethod
from ftplib import FTP, FTP_TLS
import os
import io
import pymongo
from pymongo import MongoClient


class BaseHandler(object):
    def __init__(self):
        self.byte_data = None
        self.str_data = None
        self.user = None
        self.password = None
        self.auth_addon = None

    def set_auth(self, username=None, password=None, additional=None):
        self.user = username
        self.password = password
        self.auth_addon = additional

    def save_byte_data(self, byte_data, **kwargs):
        self.byte_data = byte_data

    def save_str(self, str_data, **kwargs):
        self.str_data = str_data

    @abstractmethod
    def save(self, *args, **kwargs):
        pass


class HDFSHandler(BaseHandler):
    def __init__(self):
        super(HDFSHandler, self).__init__()

    def save(self, *args, **kwargs):
        pass

    def _save(self, file_name, file_path):
        pass


class HBaseHandler(BaseHandler):
    def __init__(self):
        super(HDFSHandler, self).__init__()

    def save(self, *args, **kwargs):
        pass

    def _save(self, file_name, file_path):
        pass


class FTPHandler(BaseHandler):
    def __init__(self, ftp_path):
        super(FTPHandler, self).__init__()
        self.ftp_client = None
        self.ftp_path = ftp_path

    def create_client(self, _ftp):
        if self.user is None:
            _ftp.login()
        else:
            _ftp.login(self.user, self.password)
        _ftp.set_pasv(True)

    def _save(self, _ftp, file_name, file_path):
        def try_create_dir(dir):
            try:
                _ftp.mkd(dir)
            except:
                pass

        def split_path(path):
            folders = []
            while 1:
                path, folder = os.path.split(path)

                if folder != "":
                    folders.append(folder)
                else:
                    if path != "":
                        folders.append(path)

                    break

            folders.reverse()
            return folders

        [(try_create_dir(i), _ftp.cwd(i)) for i in split_path(file_path)]
        self.upload(_ftp, file_name)

    def save_once(self, file_name, file_path, is_tls=False):
        try:
            if not is_tls:
                with FTP(self.ftp_path) as ftp_client:
                    self.create_client(ftp_client)
                    self._save(ftp_client, file_name, file_path)
            else:
                with FTP_TLS(self.ftp_path) as ftp_client:
                    self.create_client(ftp_client)
                    self._save(ftp_client, file_name, file_path)
        except Exception as e:
            import traceback
            traceback.print_exc()
            ftp_client.close()

    def upload(self, _ftp, file_name):
        if self.str_data is not None:
            _ftp.storlines("STOR " + file_name, io.BytesIO(self.str_data.encode("utf8")))
        else:
            _ftp.storbinary("STOR " + file_name, io.BytesIO(self.byte_data))

    def login_session(self, is_tls=False):
        if is_tls:
            self.ftp_client = FTP(self.ftp_path)
        else:
            self.ftp_client = FTP_TLS(self.ftp_path)
            if self.user is None:
                self.ftp_client.login()
            else:
                self.ftp_client.login(self.user, self.password)

    def save(self, file_name, file_path):
        self._save(self.ftp_client, file_name, file_path)

    def close(self, _ftp: FTP):
        _ftp.close()


class MongoDBHandler(BaseHandler):
    def __init__(self, uri):
        super(MongoDBHandler, self).__init__()
        self.uri = uri
        self._client = None

    def create_client(self):
        self._client = MongoClient(self.uri)

    def get_client(self):
        return self._client

    def save(self, *args, **kwargs):
        pass

    def _save(self, file_name, file_path):
        pass


class FileSaveHandler(BaseHandler):
    def __init__(self):
        super(FileSaveHandler, self).__init__()

    def save(self, file_name, file_path, *args, **kwargs):
        pass

    def _save(self, file_name, file_path):
        pass


class HttpPostHandler(BaseHandler):
    def __init__(self):
        super(HttpPostHandler, self).__init__()

    def save(self, url, file, *args, **kwargs):
        pass

    def _save(self, file_name, file_path):
        pass


if __name__ == "__main__":
    import traceback


    def test_ftp():
        try:
            ftp_handler = FTPHandler("192.168.2.24")
            ftp_handler.str_data = "ewafafsdfsgadgsgsdgsdg"
            ftp_handler.set_auth("ftpuser", "ftpuser")
            ftp_handler.save_once("1.txt", "/my/leixu/d")
        except Exception as e:
            traceback.print_exc()


    # test_ftp()
    def test_mongo():
        try:
            mongo_handler = MongoDBHandler("mongodb://192.168.2.24")
            mongo_handler.create_client()
            # 注意这里的key只能是字符串，不要使用其他类型
            mongo_handler.get_client().mydb.test.insert_one({"1": 1})
        except Exception as e:
            traceback.print_exc()


            # test_mongo()
